/**
 * 
 */

package com.chengyu.eyc.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.chengyu.eyc.base.AbstractEnums;
import com.chengyu.eyc.base.ResponseResult;
import com.chengyu.eyc.base.SelectOption;
import com.chengyu.eyc.constant.EycConstants;
import com.chengyu.eyc.enums.OrderStatusEnum;
import com.chengyu.eyc.enums.PayStatusEnum;
import com.chengyu.eyc.enums.PublishInfoStatusEnum;
import com.chengyu.eyc.jexl.JexlOrderFunction;
import com.chengyu.eyc.model.EycDataConfig;
import com.chengyu.eyc.model.EycInspPriceRule;
import com.chengyu.eyc.model.EycInspStation;
import com.chengyu.eyc.model.EycOrder;
import com.chengyu.eyc.model.EycPublicInfo;
import com.chengyu.eyc.model.EycUser;
import com.chengyu.eyc.service.EycBaseService;
import com.chengyu.eyc.service.EycService;
import com.chengyu.eyc.service.MessageService;
import com.chengyu.eyc.service.SmsService;
import com.chengyu.eyc.utils.ExcelUtils;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@RequestMapping("eyc")
@RestController
public class EycController extends AbstractBaseController {

    @Autowired
    RabbitTemplate rabbitTemplate; // 使用RabbitTemplate,这提供了接收/发送等等方法

    @Autowired
    SmsService smsService;

    @Autowired
    EycService eycService;

    @Autowired
    EycBaseService eycBasicService;
    
    @Autowired
    MessageService messageService;

    @PostMapping("auditRejectOrder")
    public ResponseResult<EycOrder> auditRejectOrder(@RequestBody EycOrder eycOrder) {
        eycOrder.setStatus(OrderStatusEnum.REJECT.getCode());
        eycOrder.setPayStatus(PayStatusEnum.PAID.getCode());
        eycOrder=  this.eycService.updateEycOrder(eycOrder);
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("value", "您好,您的退款申请被拒绝");
        dataMap.put("first", valueMap);
        valueMap = new HashMap<>();
        valueMap.put("value", eycOrder.getOrderNum());
        dataMap.put("keyword1", valueMap);
        valueMap = new HashMap<>();
        valueMap.put("value", "车辆年检");
        dataMap.put("keyword2", valueMap);
        valueMap = new HashMap<>();
        valueMap.put("value",eycOrder.getAuditRemark());
        dataMap.put("keyword3", valueMap);
        valueMap = new HashMap<>();
        valueMap.put("value","请联系客服进行沟通");
        dataMap.put("remark", valueMap);
        messageService.pushOrderRejectRefundMessage(eycOrder.getOpenid(), dataMap);
        return ResponseResult.ok(eycOrder);
    }

    @SuppressWarnings({"unchecked"})
    @GetMapping("configTypeEnums")
    public ResponseResult<List<SelectOption>> configTypeEnums(final String enumName) {
        List<SelectOption> selectOptions = null;
        Class<Enum<?>> clazz;
        try {
            clazz = (Class<Enum<?>>)Class.forName("com.chengyu.eyc.enums." + enumName);
            Enum<?>[] enums = clazz.getEnumConstants();
            selectOptions = new ArrayList<>();
            for (Enum<?> enum1 : enums) {
                AbstractEnums<String> abstractEnums = (AbstractEnums<String>)enum1;
                selectOptions.add(new SelectOption(abstractEnums.getCode(), abstractEnums.getName()));
            }

        } catch (ClassNotFoundException e) {
           log.error(e.getMessage(), e);
        }

        return ResponseResult.ok(selectOptions);
    }

    @ApiOperation("删除轮播图")
    @PostMapping("deleteCarouselImage")
    public ResponseResult<EycPublicInfo> deleteCarouselImage(@RequestBody String publicInfoId) {
        EycPublicInfo eycPublicInfo= this.eycBasicService.searchPublishInfoById(publicInfoId);
        eycPublicInfo.setStatus(PublishInfoStatusEnum.DELETE.getCode());
        return ResponseResult.ok(this.eycBasicService.updatehPublishInfoStatus(eycPublicInfo));
    }

    @ApiOperation("删除商户")
    @PostMapping("deleteInspStation")
    public ResponseResult<EycInspStation> deleteInspStation(@RequestBody EycInspStation eycInspStation) {
        return ResponseResult.ok(this.eycBasicService.deleteInspStation(eycInspStation));
    }

    @GetMapping("exportOrder")
    public void exportOrder(HttpServletResponse response, Map<String,Object> params) {
        try (OutputStream os = response.getOutputStream(); InputStream is = getInputStream("orderList.xlsx")) {
            preProcessResponse(response, "订单列表");
            Map<String, Object> functionMap = new HashMap<>(1);
            functionMap.put("fun", new JexlOrderFunction());
            List<Map<String, Object>> vWblDocSrchRsts = this.eycService.exportOrder(params);
            ExcelUtils.writeExcel(is, vWblDocSrchRsts, os, functionMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private InputStream getInputStream(String fileName) {
        return this.getClass().getClassLoader()
            .getResourceAsStream(File.separator + EycConstants.EXCEL_TEMPLATE + fileName);
    }

    @ApiOperation("新增或修改商户")
    @PostMapping("insertOrUpdateInspStation")
    public ResponseResult<EycInspStation> insertOrUpdateInspStation(@RequestBody EycInspStation eycInspStation) {
        return ResponseResult.ok(this.eycBasicService.insertOrUpdateInspStation(eycInspStation));
    }
    
    private void preProcessResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.reset();
        setResponse(response, "multipart/form-data", new String(fileName.getBytes("GB2312"), StandardCharsets.ISO_8859_1) + ".xlsx");
    }
    
    @ApiOperation("发布轮播图")
    @PostMapping("publishCarouselImage")
    public ResponseResult<EycPublicInfo> publishCarouselImage(@RequestBody String publicInfoId) {
        EycPublicInfo eycPublicInfo= this.eycBasicService.searchPublishInfoById(publicInfoId);
        eycPublicInfo.setStatus(PublishInfoStatusEnum.FILE.getCode());
        eycPublicInfo.setPublishTime(new Date());
        return ResponseResult.ok(this.eycBasicService.updatehPublishInfoStatus(eycPublicInfo));
    }
    @ApiOperation("下架轮播图")
    @PostMapping("pullOffCarouselImage")
    public ResponseResult<EycPublicInfo> pullOffCarouselImage(@RequestBody String publicInfoId) {
        EycPublicInfo eycPublicInfo= this.eycBasicService.searchPublishInfoById(publicInfoId);
        eycPublicInfo.setStatus(PublishInfoStatusEnum.DRAFT.getCode());
        return ResponseResult.ok(this.eycBasicService.updatehPublishInfoStatus(eycPublicInfo));
    }
    
    /**
     * @param params
     * @return
     */
    @ApiOperation("分页查询基础数据配置")
    @PostMapping("searchDataConfigs")
    public ResponseResult<PageInfo<EycDataConfig>> searchDataConfigs(@RequestBody Map<String, Object> params) {
        return ResponseResult.ok(this.eycBasicService.searchDataConfigs(params));
    }

    
    @ApiOperation("查询年检价格配置")
    @PostMapping("searchInspPriceRules")
    public ResponseResult<List<EycInspPriceRule>> searchInspPriceRules(@RequestBody(required = false) Map<String, Object> params) {
        return ResponseResult.ok(this.eycService.searchInspPriceRules(params));
    }
   
    @ApiOperation("查询商户列表")
    @PostMapping("searchInspStations")
    public ResponseResult<PageInfo<EycInspStation>> searchInspStations(@RequestBody Map<String, Object> params) {
        return ResponseResult.ok(this.eycBasicService.searchInspStations(params));
    }

    @ApiOperation("查询订单列表")
    @PostMapping("searchOrders")
    public ResponseResult<PageInfo<Map<String, Object>>> searchOrders(@RequestBody Map<String, Object> params) {
        return ResponseResult.ok(this.eycService.searchOrders(params));
    }
    
    @ApiOperation("查询轮播图配置页面")
    @GetMapping("searchPageConfigByTypeCde")
    public ResponseResult<List<EycPublicInfo>> searchPageConfigByTypeCde(String pageCde, String typeCde,@RequestParam(name="status", required = false) String status) {
        return ResponseResult.ok(this.eycBasicService.searchPageConfigByTypeCde(pageCde, typeCde,status));
    }
    
    @ApiOperation("查询轮播图配置页面")
    @PostMapping("searchPublishInfoPageByTypeCde")
    public ResponseResult<List<EycPublicInfo>> searchPublishInfoPageByTypeCde(@RequestBody String typeCde) {
        return ResponseResult.ok(this.eycBasicService.searchPublishInfoPageByTypeCde(typeCde));
    }
    
    @ApiOperation("查询客户列表")
    @PostMapping("searchUsers")
    public ResponseResult<PageInfo<EycUser>> searchUsers(@RequestBody Map<String, Object> params) {
        return ResponseResult.ok(this.eycService.searchUsers(params));
    }
    @GetMapping("sendDirectMessage")
    public ResponseResult<Object> sendDirectMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        // 将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
        return ResponseResult.ok();
    }
    private void setResponse(HttpServletResponse response, String contentType, String fileName) {
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attachment; filename=" + fileName);
    }
    @PostMapping("verificationOrders")
    public ResponseResult<Boolean> verificationOrders(@RequestBody List<String> orderNums) {
        return ResponseResult.ok(this.eycService.verificationOrders(orderNums));
    }
  
}
